package com.cnhaimei.vod.logic;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.cnhaimei.com.SearchTextView;
import com.cnhaimei.com.widget.ViewFlow;
import com.cnhaimei.vod.FavoriteManager;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.SelSongsManager;
import com.cnhaimei.vod.bean.Song;
import com.cnhaimei.vod.net.XVod;
import com.cnhaimei.vod.net.dc.Player;
import com.cnhaimei.vod.util.Const;

public class FavoriteActivity extends VODActivity{

	private View mHeadView;
	private SearchTextView mSearchView;
	private View mCancelView;
	private boolean mSearchViewFocused = false;
	private ViewFlow mViewFlow;
	private ListView mListView;
	private static List<Song> mSongList = new ArrayList<Song>();
	private LayoutInflater mInflater;
	private static FavoriteAdapter mListAdapter;
	private View curSelView;
	private int curSelPosition;
	
	private View mSelSongView;//更多菜单选中的项，用于onActivityResult时selectItem用
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.v8_favorites);
		initView();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		XVod.G().registerListener(EventsManager.Event.SELECT_SONG_RESULT, this);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		XVod.G().unRegisterListener(EventsManager.Event.SELECT_SONG_RESULT, this);
	}
	
	@Override
	public void onEvent(int event, Object obj, boolean isSuc) {
		// TODO Auto-generated method stub
		switch (event) {
		case EventsManager.Event.SELECT_SONG_RESULT:
			String str = (String)obj;
			if (str.equals("0")) {
				showMyToast("点播歌曲成功");
			}
			else if (str.equals("-1")) {
				showMyToast("歌曲已在‘已选’列表中");
			} 
			else {
				showMyToast("点播歌曲失败，请重试");
			}
			break;

		default:
			break;
		}
		super.onEvent(event, obj, isSuc);
	}

	private void initView() {
		//显示后退按钮
		showBackBtn(true);
		setTitle("私人收藏");

		mInflater = LayoutInflater.from(this);
		mSearchView = (SearchTextView) findViewById(R.id.search_edit);
		mCancelView = findViewById(R.id.cancel_btn);
		mHeadView = findViewById(R.id.head);
		//mViewFlow = (ViewFlow) findViewById(R.id.viewflow);		
		mListView = (ListView) findViewById(R.id.list);

		if (mCancelView != null) {
			mCancelView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mSearchView != null) {
						mSearchView.clearFocus();
						mCancelView.setVisibility(View.GONE);
						mHeadView.setVisibility(View.VISIBLE);
					}
				}
			});
		}
		if (mSearchView != null) {
			mSearchView.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					// TODO Auto-generated method stub
					mSearchViewFocused = hasFocus;
				}
			});
			mSearchView.addTextChangedListener(new SearchTextChangedListener(mSearchView));
			mSearchView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mSearchViewFocused) {
						mCancelView.setVisibility(View.VISIBLE);
						mHeadView.setVisibility(View.GONE);
					}
				}
			});
			mSearchView.setOnKeyListener(new OnKeyListener() {
				
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					// TODO Auto-generated method stub
					if(event.getAction() == KeyEvent.ACTION_UP && keyCode==KeyEvent.KEYCODE_ENTER){//修改回车键功能
						String search = mSearchView.getText().toString();
						search = search.trim();
						if (search.length() > 0) {

							// 先隐藏键盘
							((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
											FavoriteActivity.this
											.getCurrentFocus()
											.getWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

							//搜索
						}
					}
				
					return false;					
				}
			});
		}
		
		//显示歌曲
		if (!FavoriteManager.G().isLoaded()) {
			FavoriteManager.G().load();
		}
		mSongList.clear();
		mSongList.addAll(FavoriteManager.G().getList());
		mListAdapter = new FavoriteAdapter();
		mListView.setAdapter(mListAdapter);
		mListView.setCacheColorHint(Color.TRANSPARENT);
		mListView.setAlwaysDrawnWithCacheEnabled(true);
		
		/*
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				selectItem(view, position);
			}
		});
		*/
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Song tmpSong = null;
		if (data != null){
			int nPos = data.getIntExtra(Const.Key.SONG_INDEX, -1);
			if (nPos > -1 && nPos < mSongList.size()) {
				tmpSong = mSongList.get(nPos);
			}
			else {
				tmpSong = (Song)data.getSerializableExtra(Const.Key.SONG_INFO);
			}
			if (tmpSong == null) {
				return;
			}
		}
		if (requestCode == Const.RequestCode.FAVORITE_MORE)
		{
			switch(resultCode)
			{
			case Const.ResultCode.SEL_SONG:
				XVod.G().insertSong(tmpSong);
				if (mSelSongView != null) {
					selectSongName(mSelSongView);
				}
				showMyToast("点播歌曲成功");
				break;
			case Const.ResultCode.INSERT_SONG:
				final Player p = Player.G();
				if (p.getPlaylistCount() < Player.MAX_SEL) {
					int count = p.getPlaylistCount();
					XVod.G().insertSong(tmpSong);
					XVod.G().preSortSong(count, 1); 
				}
				if (mSelSongView != null) {
					selectSongName(mSelSongView);
				}
				showMyToast("插播歌曲置顶成功");
				break;
			case Const.ResultCode.SEL_SINGER:
				StarSongsActivity.starActivity(FavoriteActivity.this, tmpSong.getSinger());
				break;
			case Const.ResultCode.DELETE_SONG:
				showDeleteAlert(tmpSong);
				break;
			}
		}
	}	
	
	private class FavoriteAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mSongList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;		 
			
			if (convertView == null) {			 
				convertView = mInflater.inflate(R.layout.v8_favorite_list_item, null);
				holder = new ViewHolder();
				holder.orderView = (TextView) convertView.findViewById(R.id.order);
				holder.nameView = (TextView) convertView.findViewById(R.id.name);
				holder.singerView = (TextView) convertView.findViewById(R.id.singer);
				holder.insertView = convertView.findViewById(R.id.insert);
				holder.deleteView = convertView.findViewById(R.id.access);
				holder.operateView = convertView.findViewById(R.id.operate);
				convertView.setTag(holder);
				LayoutParams lp = convertView.getLayoutParams();
				if (lp == null) {
					lp = new AbsListView.LayoutParams(LayoutParams.FILL_PARENT, 70);
				}
				lp.height = 70;
				convertView.setLayoutParams(lp);
			} else {		
				holder = (ViewHolder) convertView.getTag();			 
			}

			holder.orderView.setText(String.valueOf(position + 1));
			holder.nameView.setText(mSongList.get(position).getName());
			holder.singerView.setText(mSongList.get(position).getSingerName());
			holder.insertView.setClickable(true);
			holder.insertView.setTag(position);
			holder.deleteView.setClickable(true);
			holder.deleteView.setTag(position);
			holder.nameView.setClickable(true);
			holder.nameView.setTag(position);
			//holder.singerView.setClickable(true);
			holder.insertView.setOnClickListener(mItemClickListener);
			holder.deleteView.setOnClickListener(mItemClickListener);
			//holder.singerView.setOnClickListener(mItemClickListener);
			holder.nameView.setOnClickListener(mItemClickListener);
			
			if (SelSongsManager.G().isSongSelected(mSongList.get(position))) {
				selectSongName(convertView);
			}
			else {
				unselectSongName(convertView);
			}
			
			/*
			if (curSelPosition != position) {
				unselectItem(convertView);
			}
			else {
				selectItem(convertView, position);
			}
			*/
			return convertView;
		}

	}
	static class ViewHolder {		 
		TextView orderView;	 
		TextView nameView;	 
		TextView singerView;	 
		View insertView;	 
		View deleteView;
		View operateView;
	}

	//当歌曲已经被点歌过的时候该歌曲名高亮
	private void selectSongName(View itemRoot) {
		if (itemRoot != null) {
			ViewHolder vhOld = (ViewHolder) itemRoot.getTag();
			vhOld.nameView.setSelected(true);
		}
	}
	
	private void unselectSongName(View itemRoot) {
		if (itemRoot != null) {
			ViewHolder vhOld = (ViewHolder) itemRoot.getTag();
			vhOld.nameView.setSelected(false);
		}
	}
	
	private void unselectItem(View itemRoot) {
		if (itemRoot != null) {
			ViewHolder vhOld = (ViewHolder) itemRoot.getTag();
			itemRoot.setBackgroundDrawable(null);
			vhOld.operateView.setVisibility(View.GONE);
			vhOld.orderView.setSelected(false);
			vhOld.singerView.setSelected(false);
			//vhOld.nameView.setSelected(false);
		}
		if (curSelView == itemRoot) {
			curSelView = null;
		}
	}
	
	private boolean selectItem(View itemRoot, int pos) {
		curSelPosition = pos;
		if (curSelView == itemRoot) {
			return false;
		}
		unselectItem(curSelView);
		curSelView = itemRoot;
		if (curSelView != null) {
			ViewHolder vh = (ViewHolder) curSelView.getTag();
			if (vh != null) {
				boolean isGone = vh.operateView.getVisibility() != View.VISIBLE;
				curSelView.setBackgroundResource(R.drawable.choosing);
				vh.operateView.setVisibility(View.VISIBLE);
				vh.orderView.setSelected(true);
				vh.singerView.setSelected(true);
				//vh.nameView.setSelected(true);
				
				return isGone;
			}
		}
		
		return false;
	}
	
	private void unselectItem() {
		if (curSelView != null) {
			ViewHolder vhOld = (ViewHolder) curSelView.getTag();
			curSelView.setBackgroundDrawable(null);
			vhOld.operateView.setVisibility(View.GONE);
			vhOld.orderView.setSelected(false);
			vhOld.singerView.setSelected(false);
			//vhOld.nameView.setSelected(false);
		}
	}
	
	private OnClickListener mItemClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.insert: {
				if ( v.getTag() instanceof Integer) {
					//unselectItem();
					int pos = (Integer) v.getTag();
					Song song = mSongList.get(pos);
					final Player p = Player.G();
					if (p.getPlaylistCount() < Player.MAX_SEL) {
						int count = p.getPlaylistCount();
						XVod.G().insertSong(song);
						XVod.G().preSortSong(count, 1); 
					}
					showMyToast("插播歌曲置顶成功");
					selectSongName((View)v.getParent().getParent().getParent());
				}
			}
				break;
			case R.id.del: {
				if (v.getTag() instanceof Integer) {
					//unselectItem();
					int pos = (Integer) v.getTag();
					Song song = mSongList.get(pos);
					showDeleteAlert(song);
				}
			}
				break;
			case R.id.access: {
				int pos = (Integer) v.getTag();
				Song song = mSongList.get(pos);
				Intent i = new Intent(Const.Action.FavoriteMore);
				i.putExtra(Const.Key.SONG_INFO, song);
				i.putExtra(Const.Key.SONG_INDEX, pos);
				startActivityForResult(i, Const.RequestCode.FAVORITE_MORE);
				mSelSongView = (View)v.getParent().getParent().getParent();
			}
			case R.id.add: {
				if (v.getTag() instanceof Song) {
					Song s = (Song) v.getTag();
					XVod.G().insertSong(s);
				}
			}
			break;
			case R.id.singer: {
				StarSongsActivity.starActivity(FavoriteActivity.this,
						((TextView) v).getText().toString());
			}
			break;
			case R.id.name:{
				int pos = (Integer) v.getTag();
				Song song = mSongList.get(pos);
				XVod.G().insertSong(song);
				selectSongName((View)v.getParent());
			}
			break;
			default:
				break;
			}
		}
	};
	
	private void showDeleteAlert(Song song) {

		final Song delSong = song;
		AlertDialog dialog = new AlertDialog.Builder(this)
        /* 弹出窗口的最上头文字 */
        .setTitle("提示")
        /* 设置弹出窗口的信息 */
        .setMessage("是否删除该歌曲")
        .setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                        //TODO：执行删除操作
                    	FavoriteManager.G().deleteSong(delSong);
                    	mSongList.remove(delSong);
                    	mListAdapter.notifyDataSetChanged();
                    }
                })
        .setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                    	//TODO：执行取消操作
                    }
                })
        .show();
		dialog.setCanceledOnTouchOutside(false);
	}
	
	//搜索词变化监听
    public static class SearchTextChangedListener implements TextWatcher {

        private final SearchTextView txt;

        SearchTextChangedListener(final SearchTextView txt) {
            this.txt = txt;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
        	List<Song>list = FavoriteManager.G().getList();
        	String word = txt.getText().toString();
        	if (word.length() > 0) {
				mSongList.clear();
        		for (Song song : list) {
					if (song.getName().contains(word)) {
						mSongList.add(song);
					}
				}
			} else {
				mSongList.clear();
				mSongList.addAll(list);
			}
			mListAdapter.notifyDataSetChanged();
        }
    }
	
}
